package com.bigxuan.engsimple;

import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigxuan.engsimple.adapter.PageAdapter;
import com.bigxuan.engsimple.service.SoftUpdateService;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener, View.OnClickListener {

    private static final String TAG = "MainActivity";

    private RecyclerView recyclerView;
    private final List<Integer> pageList = new ArrayList<>(10);
    private TextView tvPage;
    private final LinearLayoutManager layoutManager = new LinearLayoutManager(this);

    //手势
    private GestureDetector gestureDetector;
    //pdf加载
    private PdfRenderer pdfRenderer;
    private PdfRenderer.Page currentPage;
    //显示pdf一页
    private ImageView pdfView;


    //mp3播放
    private MediaPlayer mediaPlayer;
    //播放位置
    private int currentPosition;
    //mp3文件序号 从0 开始 对应第一页
    private int audioIndex;

    private ImageButton btnFastRewind;
    private ImageButton btnPlay;
    private ImageButton btnPause;
    private ImageButton btnFastForward;

    private Timer timerToast;
    private HandlerThread threadToast = new HandlerThread("toastThread");
    private Handler handlerToast = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            String text = msg.getData().getString("text");
            Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
        }
    };

    private final String DATA_FILE_PATH = "/sdcard/engsimple";

    //手势常量
    private final int FLIP_DISTANCE = 100;
    //pdf总页数
    private int totalPageCnt;
    //pdf当前页
    private int currentPageCnt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        gestureDetector = new GestureDetector(MainActivity.this, this);

        new SoftUpdateService(this, SoftUpdateService.CHECK_USER).checkUpdate();

        initView();

        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        setPreferences();
        if (pdfRenderer != null) {
            try {
                pdfRenderer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
    }

    private long backKeyPressedTime = 0;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - backKeyPressedTime > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            backKeyPressedTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
            finish();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (recyclerView.getVisibility() == View.VISIBLE) {
            Rect outRect = new Rect();
            recyclerView.getGlobalVisibleRect(outRect);
            if (!outRect.contains((int) event.getRawX(), (int) event.getRawY())) {
                // 触摸点不在myView上，隐藏myView
                recyclerView.setVisibility(View.GONE);
                tvPage.setVisibility(View.VISIBLE);
                return true;
            }
        } else {
            return gestureDetector.onTouchEvent(event);
        }
        return false;
    }

    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float v, float v1) {
        if (e1.getX() - e2.getX() < FLIP_DISTANCE) {
            if (currentPageCnt == 0) {
                Toast.makeText(this, "已是第一页", Toast.LENGTH_SHORT).show();
                return false;
            }
            pagePrev();
            return true;

        } else if (e1.getX() - e2.getX() > FLIP_DISTANCE) {
            if (currentPageCnt == totalPageCnt - 1) {
                Toast.makeText(this, "已是最后一页", Toast.LENGTH_SHORT).show();
                return false;
            }
            pageNext();
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_fast_rewind:
                rewind();
                break;
            case R.id.btn_play:
                play();
                break;
            case R.id.btn_pause:
                pause();
                break;
            case R.id.btn_fast_forward:
                forward();
            case R.id.tv_page:
                showPageList();
                break;
        }
    }

    private void initData() {
        try {
            File file = new File(DATA_FILE_PATH + "/book.pdf");
            ParcelFileDescriptor parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
            pdfRenderer = new PdfRenderer(parcelFileDescriptor);
            totalPageCnt = pdfRenderer.getPageCount();

            for (int i = 1; i <= totalPageCnt; i++) {
                pageList.add(i);
            }

            PageAdapter adapter = new PageAdapter(pageList);
            adapter.setItemClickListener(position -> {
                currentPageCnt = position;
                audioIndex = position;
                loadPage(position);
                switchAudio();
                position++;
                String text = position > 9 ? String.format("第%d页", position) : String.format("第0%d页", position);
                tvPage.setText(text);
                recyclerView.setVisibility(View.GONE);
                tvPage.setVisibility(View.VISIBLE);

            });
            recyclerView.setAdapter(adapter);


            //获取缓存数据
            getPreferences();
            Log.i(TAG, "currentPageCnt " + currentPageCnt);


            if (pdfRenderer.getPageCount() > 0) {
                loadPage(currentPageCnt);
            }

            //最后加载音频 因为无音频文件 会抛出异常导致 翻页控价加载失败
            mediaPlayer.setDataSource(DATA_FILE_PATH + "/" + audioIndex + ".mp3"); // 替换为你的MP3文件URL
            mediaPlayer.prepare();

        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
    }

    public void initView() {

        tvPage = findViewById(R.id.tv_page);
        tvPage.setOnClickListener(this);

        pdfView = findViewById(R.id.pdf_view);

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                Log.i(TAG, "onPrepared");
            }
        });

        btnFastRewind = findViewById(R.id.btn_fast_rewind);
        btnPlay = findViewById(R.id.btn_play);
        btnPause = findViewById(R.id.btn_pause);
        btnFastForward = findViewById(R.id.btn_fast_forward);

        btnFastRewind.setOnClickListener(this);
        btnPlay.setOnClickListener(this);
        btnPause.setOnClickListener(this);
        btnFastForward.setOnClickListener(this);

        recyclerView = findViewById(R.id.rv_page);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);


    }

    private void showPageList() {

        layoutManager.scrollToPosition(currentPageCnt);
        tvPage.setVisibility(View.GONE);
        recyclerView.setVisibility(View.VISIBLE);
    }

    private void play() {
        Log.i(TAG, "play");
        mediaPlayer.start();
        btnPlay.setVisibility(View.GONE);
        btnPause.setVisibility(View.VISIBLE);
    }

    private void pause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            currentPosition = mediaPlayer.getCurrentPosition();
        } else {
            mediaPlayer.start();
            mediaPlayer.seekTo(currentPosition);
        }
        btnPlay.setVisibility(View.VISIBLE);
        btnPause.setVisibility(View.GONE);
    }

    private void forward() {
        if (mediaPlayer.isPlaying()) {
            int newPosition = mediaPlayer.getCurrentPosition() + 10000; // 快进10秒
            if (newPosition >= mediaPlayer.getDuration()) {
                newPosition = mediaPlayer.getDuration() - 1;
            }
            mediaPlayer.seekTo(newPosition);
        }
    }

    private void rewind() {
        if (mediaPlayer.isPlaying()) {
            int newPosition = mediaPlayer.getCurrentPosition() - 10000; // 快退10秒
            if (newPosition < 0) {
                newPosition = 0;
            }
            mediaPlayer.seekTo(newPosition);
        }
    }

    private void switchAudio() {
        pause();
        mediaPlayer.reset();
        try {
            String path = DATA_FILE_PATH + "/" + audioIndex + ".mp3";
            File file = new File(path);
            if (!file.exists()) {
                if (timerToast != null) {
                    timerToast.cancel();
                }
                timerToast = new Timer();
                timerToast.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        Message message = Message.obtain();
                        Bundle bundle = new Bundle();
                        bundle.putString("text", audioIndex + ".mp3 文件不存在");
                        message.setData(bundle);
                        handlerToast.sendMessage(message);
                    }
                }, 1500);
                return;
            }
            mediaPlayer.setDataSource(DATA_FILE_PATH + "/" + audioIndex + ".mp3");
            mediaPlayer.prepare();
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
        }
    }

    /**
     * 加载一页pdf
     *
     * @param page 页
     */
    private void loadPage(int page) {
        if (page < 0 || page > totalPageCnt - 1) {
            return;
        }
        Log.i(TAG, "page = " + page + "  totalPageCnt = " + totalPageCnt);
        currentPage = pdfRenderer.openPage(page); // 打开第一页
        currentPageCnt = currentPage.getIndex();
        Bitmap bitmap = Bitmap.createBitmap(currentPage.getWidth(), currentPage.getHeight(), Bitmap.Config.ARGB_8888);
        currentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        pdfView.setImageBitmap(bitmap);
        currentPage.close();
        page++;
        String text = page < 10 ? "0" + page : "" + page;
        tvPage.setText(MessageFormat.format("第{0}页", text));
    }

    /**
     * 前一页
     */
    private void pagePrev() {
        audioIndex--;
        switchAudio();
        loadPage(currentPageCnt - 1);
    }

    /**
     * 后一页
     */
    private void pageNext() {
        audioIndex++;
        switchAudio();
        loadPage((currentPageCnt + 1));
    }

    /**
     * 缓存当前页数
     */
    private void setPreferences() {
        SharedPreferences.Editor editor = getSharedPreferences(TAG, MODE_PRIVATE).edit();
        editor.putInt("currentPageCnt", currentPageCnt);
        editor.apply();
    }

    /**
     * 读取当前页数
     */
    private void getPreferences() {
        SharedPreferences sharedPreferences = getSharedPreferences(TAG, MODE_PRIVATE);
        currentPageCnt = sharedPreferences.getInt("currentPageCnt", 0);
        audioIndex = currentPageCnt;
    }

}